import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:stacked/stacked.dart';
import 'package:vista/app/di/injection.dart';
import 'package:vista/app/router/app_router.dart';
import 'package:vista/main.dart' as app;
import 'package:vista/shared/constants/color.dart';
import 'package:vista/shared/utils/widget_extension.dart';
import 'package:vista/shared/widgets/vacant_state.dart';
import 'package:vista/features/message/viewmodels/message_viewmodel.dart';
import 'package:vista/shared/models/user_frame.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/circle_gallery.dart';
import 'package:vista/shared/services/dialog_lens.dart';
import 'package:vista/shared/services/relation_bond.dart';

/// 消息视图
/// 消息功能页面，显示朋友列表、单聊列表和群聊列表
class MessageView extends StatefulWidget {
  const MessageView({super.key});

  @override
  State<MessageView> createState() => _MessageViewState();
}

class _MessageViewState extends State<MessageView>
    with WidgetsBindingObserver, RouteAware {
  MessageViewModel? _viewModel;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final route = ModalRoute.of(context);
    if (route is PageRoute) {
      app.routeObserver.subscribe(this, route);
    }
  }

  @override
  void dispose() {
    app.routeObserver.unsubscribe(this);
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // 当应用从后台恢复时，刷新登录状态
    if (state == AppLifecycleState.resumed && _viewModel != null) {
      _viewModel!.refresh();
    }
  }

  @override
  void didPopNext() {
    // 当从其他页面返回到此页面时刷新
    if (_viewModel != null) {
      _viewModel!.refresh();
    }
  }

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<MessageViewModel>.reactive(
      viewModelBuilder:
          () => MessageViewModel(
            getIt.get<AuthFocus>(),
            getIt.get<RelationBond>(),
            getIt.get<DialogLens>(),
            getIt.get<CircleGallery>(),
          )..initialize(),
      onViewModelReady: (viewModel) {
        _viewModel = viewModel;
      },
      builder: (context, viewModel, child) {
        return Scaffold(
          body: Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/my-background.png'),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(
              child:
                  viewModel.isBusy
                      ? const Center(child: CircularProgressIndicator())
                      : viewModel.currentUser == null
                      ? _buildLoginPrompt(context, viewModel)
                      : _buildContent(context, viewModel),
            ),
          ),
        );
      },
    );
  }

  /// 构建登录提示
  Widget _buildLoginPrompt(BuildContext context, MessageViewModel viewModel) {
    return [
          VacantState(
            message: 'Please login to view messages',
            imagePath: 'assets/images/empty1.png',
          ),
          SizedBox(height: 32.h),
          // 登录按钮
          ElevatedButton(
            onPressed: () async {
              // 使用 Navigator.push 等待返回结果
              await Navigator.of(context).pushNamed(Routes.login);
              // 从登录页面返回后，didPopNext() 会自动刷新，这里不需要手动刷新
            },
            style: ElevatedButton.styleFrom(
              padding: EdgeInsets.symmetric(horizontal: 48.w, vertical: 16.h),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12.r),
              ),
              backgroundColor: ColorConstants.accentColor,
              foregroundColor: Colors.white,
              elevation: 0,
            ),
            child: Text(
              'Login',
              style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w600),
            ),
          ),
        ]
        .verticalShot(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
        )
        .frameHorizontal(24.w);
  }

  /// 构建内容
  Widget _buildContent(BuildContext context, MessageViewModel viewModel) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 固定的标题
        Padding(
          padding: EdgeInsets.fromLTRB(14.w, 0.h, 14.w, 14.w),
          child: Center(
            child: Text(
              'Message',
              style: TextStyle(
                fontSize: 20.sp,
                fontFamily:
                    GoogleFonts.alegreyaSans(
                      fontWeight: FontWeight.w800,
                    ).fontFamily,
                color: Colors.black87,
              ),
            ),
          ),
        ),
        // 可滚动的内容
        Expanded(
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white.withValues(alpha: 0.40),
              borderRadius: BorderRadius.circular(16.r),
              border: Border.all(
                color: Colors.black.withOpacity(0.1),
                width: 1,
              ),
            ),
            child: SingleChildScrollView(
              padding: EdgeInsets.all(14.w),
              child: [
                // My Friends 卡片
                _buildFriendsCard(context, viewModel),
                SizedBox(height: 14.w),
                // Dialogue 卡片
                _buildDialogueCard(context, viewModel),
                SizedBox(height: 14.w),
                // My Group 卡片
                _buildGroupCard(context, viewModel),
                SizedBox(height: 80.h), // 底部留白，防止被导航栏遮住
              ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
            ),
          ).frameHorizontal(14.w),
        ),
      ],
    );
  }

  /// 构建朋友列表卡片
  Widget _buildFriendsCard(BuildContext context, MessageViewModel viewModel) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        color: ColorConstants.primaryColor,
        borderRadius: BorderRadius.circular(16.r),
      ),
      padding: EdgeInsets.all(14.w),
      child: [
        // 标题
        Text(
          'My Friends',
          style: TextStyle(
            fontSize: 18.sp,
            fontFamily:
                GoogleFonts.alegreyaSans(
                  fontWeight: FontWeight.w800,
                ).fontFamily,
            color: Colors.black87,
          ),
        ),
        SizedBox(height: 10.w),
        // 朋友列表
        viewModel.friends.isEmpty
            ? Padding(
              padding: EdgeInsets.symmetric(vertical: 14.w),
              child: Text(
                'No friends yet',
                style: TextStyle(fontSize: 14.sp, color: Colors.grey[600]),
              ),
            )
            : SizedBox(
              height: 60.h,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: viewModel.friends.length + 1,
                itemBuilder: (context, index) {
                  if (index == viewModel.friends.length) {
                    // 更多按钮
                    return GestureDetector(
                      onTap: () async {
                        await Navigator.of(
                          context,
                        ).pushNamed(Routes.friendsList);
                        // 返回时刷新数据
                        await viewModel.refresh();
                      },
                      child: Padding(
                        padding: EdgeInsets.only(left: 8.w),
                        child: Container(
                          width: 42.w,
                          height: 42.w,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            color: ColorConstants.primaryColor2,
                          ),
                          padding: EdgeInsets.all(10.w),
                          child: Image.asset(
                            'assets/images/chevron_right_rounded.png',
                          ),
                        ),
                      ),
                    );
                  }
                  final friend = viewModel.friends[index];
                  return Padding(
                    padding: EdgeInsets.only(
                      right: index < viewModel.friends.length - 1 ? 8.w : 0,
                    ),
                    child: _buildFriendAvatar(context, viewModel, friend),
                  );
                },
              ),
            ),
      ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
    );
  }

  /// 构建朋友头像
  Widget _buildFriendAvatar(
    BuildContext context,
    MessageViewModel viewModel,
    UserFrame friend,
  ) {
    return GestureDetector(
      onTap: () async {
        // 检查是否有对话
        final hasChat = await viewModel.hasChatWithUser(friend.id);
        if (!hasChat) {
          // 没有对话，先创建对话
          await viewModel.createChatWithUser(friend.id);
        }
        // 跳转到聊天页面
        if (context.mounted) {
          await Navigator.of(
            context,
          ).pushNamed(Routes.chat, arguments: {'otherUserId': friend.id});
          // 返回时刷新数据
          if (context.mounted) {
            await viewModel.refresh();
          }
        }
      },
      child: SizedBox(
        width: 42.w,
        height: 42.w,
        child: CircleAvatar(
          radius: 21.r,
          backgroundColor: Colors.white,
          backgroundImage:
              friend.avatar != null ? AssetImage(friend.avatar!) : null,
          child:
              friend.avatar == null
                  ? Icon(Icons.person, size: 21.w, color: Colors.grey)
                  : null,
        ),
      ),
    );
  }

  /// 构建单聊列表卡片
  Widget _buildDialogueCard(BuildContext context, MessageViewModel viewModel) {
    return Container(
      decoration: BoxDecoration(
        color: ColorConstants.primaryColor.withOpacity(0.7),
        borderRadius: BorderRadius.circular(16.r),
      ),
      padding: EdgeInsets.all(14.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题
          Text(
            'Dialogue',
            style: TextStyle(
              fontSize: 18.sp,
              fontFamily:
                  GoogleFonts.alegreyaSans(
                    fontWeight: FontWeight.w800,
                  ).fontFamily,
              color: Colors.black87,
            ),
          ),
          SizedBox(height: 14.w),
          // 单聊列表
          if (viewModel.chatSessions.isEmpty)
            VacantState(
              message: 'No messages yet',
              imagePath: 'assets/images/empty2.png',
            )
          else
            ...viewModel.chatSessions
                .asMap()
                .entries
                .map((entry) {
                  final index = entry.key;
                  final session = entry.value;
                  return [
                    _buildChatSessionItem(context, viewModel, session),
                    if (index < viewModel.chatSessions.length - 1)
                      SizedBox(height: 14.w),
                  ];
                })
                .expand((list) => list),
        ],
      ),
    );
  }

  /// 构建单聊会话项
  Widget _buildChatSessionItem(
    BuildContext context,
    MessageViewModel viewModel,
    session,
  ) {
    final lastMessage = session.lastMessage;
    final messageContent = lastMessage?.content ?? '';
    final messageTime =
        lastMessage != null
            ? DateFormat('HH:mm').format(lastMessage.timestamp)
            : '';

    return GestureDetector(
      onTap: () async {
        await Navigator.of(
          context,
        ).pushNamed(Routes.chat, arguments: {'otherUserId': session.user.id});
        // 返回时刷新数据
        await viewModel.refresh();
      },
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8.r),
          border: Border.all(color: Colors.black, width: 1),
        ),
        padding: EdgeInsets.all(14.w),
        child: Row(
          children: [
            // 头像
            GestureDetector(
              onTap: () async {
                // 检查是否是当前用户
                final currentUser = await getIt<AuthFocus>().getCurrentUser();
                if (currentUser != null && currentUser.id == session.user.id) {
                  return; // 是自己的头像，不跳转
                }
                // 跳转到他人主页
                if (context.mounted) {
                  await Navigator.of(context).pushNamed(
                    Routes.otherProfile,
                    arguments: {'userId': session.user.id},
                  );
                }
              },
              child: SizedBox(
                width: 46.w,
                height: 46.w,
                child: CircleAvatar(
                  radius: 23.r,
                  backgroundColor: Colors.grey[200],
                  backgroundImage:
                      session.user.avatar != null
                          ? AssetImage(session.user.avatar!)
                          : null,
                  child:
                      session.user.avatar == null
                          ? Icon(Icons.person, size: 23.w, color: Colors.grey)
                          : null,
                ),
              ),
            ),
            SizedBox(width: 14.w),
            // 内容
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    session.user.username,
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontFamily:
                          GoogleFonts.alegreyaSans(
                            fontWeight: FontWeight.w800,
                          ).fontFamily,
                      color: Colors.black87,
                    ),
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    messageContent.isNotEmpty
                        ? messageContent.length > 30
                            ? '${messageContent.substring(0, 30)}...'
                            : messageContent
                        : 'No messages',
                    style: TextStyle(fontSize: 14.sp, color: Colors.grey[600]),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
            // 时间和未读数
            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                if (messageTime.isNotEmpty)
                  Text(
                    messageTime,
                    style: TextStyle(fontSize: 12.sp, color: Colors.grey[600]),
                  ),
                if (session.unreadCount > 0) ...[
                  SizedBox(height: 4.h),
                  Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 6.w,
                      vertical: 2.h,
                    ),
                    decoration: BoxDecoration(
                      color: ColorConstants.accentColor,
                      borderRadius: BorderRadius.circular(10.r),
                    ),
                    child: Text(
                      session.unreadCount > 99
                          ? '99+'
                          : '${session.unreadCount}',
                      style: TextStyle(
                        fontSize: 10.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ],
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建群聊列表卡片
  Widget _buildGroupCard(BuildContext context, MessageViewModel viewModel) {
    return Container(
      decoration: BoxDecoration(
        color: ColorConstants.primaryColor.withOpacity(0.7),
        borderRadius: BorderRadius.circular(16.r),
      ),
      padding: EdgeInsets.all(14.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题
          Text(
            'My Group',
            style: TextStyle(
              fontSize: 18.sp,
              fontFamily:
                  GoogleFonts.alegreyaSans(
                    fontWeight: FontWeight.w800,
                  ).fontFamily,
              color: Colors.black87,
            ),
          ),
          SizedBox(height: 14.w),
          // 群聊列表
          if (viewModel.groupSessions.isEmpty)
            VacantState(
              message: 'No groups yet',
              imagePath: 'assets/images/empty1.png',
            )
          else
            ...viewModel.groupSessions
                .asMap()
                .entries
                .map((entry) {
                  final index = entry.key;
                  final session = entry.value;
                  return [
                    _buildGroupSessionItem(context, viewModel, session),
                    if (index < viewModel.groupSessions.length - 1)
                      SizedBox(height: 14.w),
                  ];
                })
                .expand((list) => list),
        ],
      ),
    );
  }

  /// 构建群聊会话项
  Widget _buildGroupSessionItem(
    BuildContext context,
    MessageViewModel viewModel,
    session,
  ) {
    final lastMessage = session.lastMessage;
    final messageContent = lastMessage?.content ?? '';
    final messageTime =
        lastMessage != null
            ? DateFormat('HH:mm').format(lastMessage.timestamp)
            : '';

    return GestureDetector(
      onTap: () async {
        await Navigator.of(
          context,
        ).pushNamed(Routes.groupChat, arguments: {'groupId': session.group.id});
        // 返回时刷新数据
        await viewModel.refresh();
      },
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8.r),
          border: Border.all(color: Colors.black, width: 1),
        ),
        padding: EdgeInsets.all(14.w),
        child: Row(
          children: [
            // 头像
            SizedBox(
              width: 46.w,
              height: 46.w,
              child: CircleAvatar(
                radius: 23.r,
                backgroundColor: Colors.grey[200],
                backgroundImage: AssetImage(session.group.image),
                child:
                    session.group.image.isEmpty
                        ? Icon(Icons.group, size: 23.w, color: Colors.grey)
                        : null,
              ),
            ),
            SizedBox(width: 14.w),
            // 内容
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    session.group.title.length > 20
                        ? '${session.group.title.substring(0, 20)}...'
                        : session.group.title,
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontFamily:
                          GoogleFonts.alegreyaSans(
                            fontWeight: FontWeight.w800,
                          ).fontFamily,
                      color: Colors.black87,
                    ),
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    messageContent.isNotEmpty
                        ? messageContent.length > 30
                            ? '${messageContent.substring(0, 30)}...'
                            : messageContent
                        : 'No messages',
                    style: TextStyle(fontSize: 14.sp, color: Colors.grey[600]),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
            // 时间
            if (messageTime.isNotEmpty)
              Text(
                messageTime,
                style: TextStyle(fontSize: 12.sp, color: Colors.grey[600]),
              ),
          ],
        ),
      ),
    );
  }
}
